from fastapi import APIRouter, HTTPException
from models.mail_model import Mail
from services.mail_service import send_email_service
import json
import logging

router = APIRouter()
logging.basicConfig(level=logging.INFO)

@router.post("/send-email/")
async def send_email(email_data: dict) -> dict:
    try:
        # 调试日志，检查传入数据
        logging.info("Received email_data: %s", email_data)

        # 获取 email_data 中的字符串
        raw_email_data = email_data.get("email_data")
        if not isinstance(raw_email_data, str):
            raise HTTPException(status_code=400, detail="Invalid email_data format. Expected a string.")

        # 移除字符串中的换行符
        sanitized_email_data = raw_email_data.replace("\n", "")

        # 将字符串解析为 JSON 格式
        try:
            parsed_email_data = json.loads(sanitized_email_data)
        except json.JSONDecodeError as e:
            logging.error("JSON parsing error: %s", str(e))
            raise HTTPException(status_code=400, detail="Failed to parse email_data string into JSON.")

        # 使用 Pydantic 模型验证数据
        mail = Mail(**parsed_email_data)
        send_email_service(mail)
        return {"message": "Email sent successfully"}
    except HTTPException as http_exc:
        raise http_exc
    except Exception as e:
        logging.error("Unexpected error: %s", str(e))
        raise HTTPException(status_code=500, detail="Internal server error")